<?php
class MapperComments
{
	public function __construct()
    {
		mysql_connect(HOST, LOGIN, PASS) or die('No connect with database');
		mysql_query('SET NAMES utf8');
		mysql_select_db(DB) or die("error");
	}

	function __destruct()
    {
		mysql_close();
	}

	public function getCommentsOnArticle($id) {
		$query = "SELECT comments.id_comment, comments.text FROM comments JOIN articles ON comments.id_article = articles.id_article WHERE comments.id_article = {$id}";
		$r = mysql_query($query) or die(mysql_error());
		$n = mysql_num_rows($r);
		$comments = array();
		for ($i = 0; $i < $n; $i++) {
			$row = mysql_fetch_assoc($r);
			$comment = new ModelComments($row);
			$comments[] = $comment;
		}
		return $comments;
	}
	/*
	public function getCountCommentsOnArticle($id) {
		$query = "SELECT comments.id_comment, comments.text FROM comments JOIN articles ON comments.id_article = articles.id_article WHERE comments.id_article = {$id}";
		$r = mysql_query($query) or die(mysql_error());
		$n = mysql_num_rows($r);
		return $n;
	}*/
	
	public function createComment($id_article, $text) {
		$text       = Validator::validatorXss($text);
		$text       = Validator::validatorSql($text);
		$id_article = Validator::validatorIdSql($id_article);
		$query = "INSERT INTO comments (id_article, text) VALUES ({$id_article}, '{$text}' )";
		$r = mysql_query($query) or die(mysql_error());
		if ($r) {
			return true;
		} else {
			return false;
		}
	}
	public function delComment($id)
    {
		$id   = Validator::validatorIdSql($id);
		$query = "DELETE FROM `comments` WHERE `id_comments` = {$id}";
		$r = mysql_query($query) or die(mysql_error());
		if ($r) {
			return true;
		} else {
			return false;
		}
	}

}
